//
//  String+Extension.swift
//  Poetry
//
//  Created by cheyongzi on 2023/12/14.
//

import Foundation

extension String{
    public var localized: String{
        return NSLocalizedString(self, comment: "")
    }
    
    public var Class: AnyClass? {
        if let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String {
            let classStringName = appName + "." + self
            return NSClassFromString(classStringName)
        }
        return nil;
    }
}

extension StringProtocol{
    func index<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
        range(of: string, options: options)?.lowerBound
    }
    func endIndex<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
        range(of: string, options: options)?.upperBound
    }
    func indices<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Index] {
        ranges(of: string, options: options).map(\.lowerBound)
    }
    func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {
        var result: [Range<Index>] = []
        var startIndex = self.startIndex
        while startIndex < endIndex,
            let range = self[startIndex...]
                .range(of: string, options: options) {
                result.append(range)
                startIndex = range.lowerBound < range.upperBound ? range.upperBound :
                    index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
        }
        return result
    }
}

extension String{
    /// 将原始的url编码为合法的url
    public func urlEncode() -> String? {
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)
        return encodeUrlString
    }
    
    /// 将编码后的url转换回原始的url
    public func urlDecode() -> String? {
        return self.removingPercentEncoding
    }
    
    /// 添加参数
    public func addQuery(with key: String, value: String)->String{
        var result = self
        if self.contains("?") {
           if self.last == "?" {
               result += "\(key)=\(value)"
           } else {
               if self.last == "&" {
                   result += "\(key)=\(value)"
               } else {
                   result += "&\(key)=\(value)"
               }
           }
        } else {
           result += "?\(key)=\(value)"
        }
        return result
    }
}


extension String{
    ///变成Int 类型
    public func toInt() -> Int? {
        if let num = NumberFormatter().number(from: self) {
            return num.intValue
        } else {
            return nil
        }
    }
    /// 变成Double 类型
    public func toDouble() -> Double? {
        if let num = NumberFormatter().number(from: self) {
            return num.doubleValue
        } else {
            return nil
        }
    }
    /// 变成Float 类型
    public func toFloat() -> Float? {
        if let num = NumberFormatter().number(from: self) {
            return num.floatValue
        } else {
            return nil
        }
    }
    /// 变成字典类型
    public func toDictionary(sep: String = ";") -> [String:String]{
        var result: [String:String] = [:]
        let values = self.split(string: sep)
        values.forEach { value in
            let subValues = value.split(separator: "=")
            guard subValues.count > 1 else{
                return
            }
            let key = subValues[0].trimmingCharacters(in: .whitespaces)
            let subValue: String = subValues[1...].joined(separator: "=")
            result[key] = subValue.urlDecode()
        }
        return result
    }
}

extension String{
    ///  字符串的截取
    public func subStringFrom(index: Int,length:Int) -> String {
        if self.count > index {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let endIndex = self.index(self.startIndex, offsetBy: index+length)
            
            let subString = self[startIndex..<endIndex]
            return String(subString)
        } else {
            return self
        }
    }
    ///  字符串的截取
    public func subString(from: Int, to: Int) -> String
    {
        let fromIndex = index(startIndex, offsetBy: from)
        let toIndex = index(startIndex, offsetBy: to)
        
        guard fromIndex >= startIndex, fromIndex < toIndex, toIndex <= endIndex else { return "" }
        
        return String(self[fromIndex ..< toIndex])
    }
    ///  字符串的截取
    public func subString(from: Int) -> String
    {
        return subString(from: from, to: count)
    }
    ///  字符串的截取
    public func subString(to: Int) -> String
    {
        return subString(from: 0, to: to)
    }
    
    ///替换指定范围内的字符串
    mutating func stringByReplacingCharactersInRange(index:Int,length:Int,replacText:String) -> String {
        let startIndex = self.index(self.startIndex, offsetBy: index)
        self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: length), with: replacText)
        return self
    }
    /// 替换指定字符串
    mutating func stringByReplacingstringByReplacingString(text:String,replacText:String) -> String {
        return self.replacingOccurrences(of: text, with: replacText)
    }
    
    ///删除最后一个字符
    mutating func deleteEndCharacters() -> String {
        self.remove(at: self.index(before: self.endIndex))
        return self
    }
    /// 删除指定字符串
    mutating func deleteString(string:String) -> String {
        return self.replacingOccurrences(of: string, with: "")
    }
    
    /// 字符的插入
    mutating func insertString(text:Character,index:Int) -> String{
        let start = self.index(self.startIndex, offsetBy: index)
        self.insert(text, at: start)
        return self
    }
    ///字符串的插入
    mutating func insertString(text:String,index:Int) -> String{
        let start = self.index(self.startIndex, offsetBy: index)
        self.insert(contentsOf: text, at: start)
        return self
    }
    
    /// 将字符串通过特定的字符串拆分为字符串数组
    ///
    /// - Parameter string: 拆分数组使用的字符串
    /// - Returns: 字符串数组
    func split(string:String) -> [String] {
        return NSString(string: self).components(separatedBy: string)
    }
}
